package com.hzsoft.sys.controller;

import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.hzsoft.base.entity.BJuiJSON;
import com.hzsoft.base.entity.Page;
import com.hzsoft.sys.entity.SysDic;
import com.hzsoft.sys.entity.SysDicKey;
import com.hzsoft.sys.service.SysDicService;
import com.hzsoft.sys.service.SysMenuService;
import com.hzsoft.util.StrUtil;

@Controller
@RequestMapping("/system/dic")
public class SysDicController extends com.hzsoft.base.BaseController{
	
	@Autowired
	SysMenuService menuService;
	@Autowired
	SysDicService dicService;
	
	
	@RequestMapping(value = "/systemDicList")
	public ModelAndView sysDicList(@ModelAttribute SysDic result,
			HttpServletResponse response, HttpServletRequest request)
			throws IOException {
		//分页设置
		String pageCurrent = request.getParameter("pageCurrent");
		Page page =  new Page();
		if (StringUtils.isNotBlank(pageCurrent)) {
			page.setPageCurrent(Integer.parseInt(pageCurrent));
			result.setPage(page);
		}
		
		String dicName = result.getDicName();
		if (dicName == null) {
			dicName = "";
		}
		Map<String,Object> map = new HashMap<String,Object>();
		map.put("dicName", dicName.trim().toUpperCase());
		map.put("obj", result);
		List<SysDic> list = dicService.listPageByDicName(map);
		Map<String, Object> model = new HashMap<String, Object>();
		model.put("list", list);
		model.put("page", result.getPage());
		return new ModelAndView("system/dic/list", model);
	}
	
	
	/**
	 * 数据字典管理：添加数据字典目录，
	 * @param dic
	 * @param response
	 * @param request
	 * @return
	 */
	@RequestMapping("/toAddDicDir")
	public ModelAndView toAddDicDir(@ModelAttribute SysDic dic,HttpServletResponse response, HttpServletRequest request){
		ModelAndView model = new ModelAndView();
	
		model.setViewName("system/dic/addDicDir");
		return model;
	}
	/**
	 * 数据字典管理：添加数据字典目录
	 * @param result
	 * @param response
	 * @param request
	 * @return
	 * @throws IOException
	 */
	@RequestMapping(value = "/addDicDir")
	public ModelAndView createDic(SysDic rec, HttpServletResponse response,
			HttpServletRequest request) throws Exception {
		BJuiJSON bjui = new BJuiJSON();
		ModelAndView mv = new ModelAndView();
		if(null != rec.getDicCode()){
			rec.setDicCode(rec.getDicCode().trim().toUpperCase());
		}
		SysDic dic = dicService.getDicByCodeOrName(rec);
		if (dic == null) {
			try {
				dicService.insert(rec);

				bjui.setStatusCode("200");
				bjui.setMessage("保存成功！！！");
				bjui.setTabid("navtab-diclis");
				bjui.setCloseCurrent(true);
			} catch (Exception e) {
				bjui.setStatusCode("300");
				bjui.setMessage("保存失败！！！");
			}
		} else {
			bjui.setStatusCode("300");
			bjui.setMessage("该项已存在！！！");
		}
		String msg = JSONObject.fromObject(bjui).toString();
		mv.addObject("msg", msg);
		mv.setViewName("msg");
		return mv;
	}
	/**
	 * 数据字典管理：添加字典项
	 * @param result
	 * @param response
	 * @param request
	 * @return
	 * @throws IOException
	 */
	@RequestMapping(value = "/addDic", method = RequestMethod.POST)
	public ModelAndView saveUser(SysDicKey key, SysDic rec,HttpServletResponse response, HttpServletRequest request) {
		ModelAndView mv = new ModelAndView();
		BJuiJSON bjui = new BJuiJSON();
		SysDicKey dicKey = dicService.selectByPrimaryKey(key);
		if (dicKey == null) {
			try {
				dicService.insert(rec);	
				
				bjui.setStatusCode("200");
				bjui.setMessage("保存成功！！！");
				bjui.setTabid("navtab-dic");
				bjui.setCloseCurrent(true);
			} catch (Exception e) {
				bjui.setStatusCode("300");
				bjui.setMessage("保存失败！！！");
			}
		} else {
			bjui.setStatusCode("300");
			bjui.setMessage("该项已存在！！！");
		}
		String msg = JSONObject.fromObject(bjui).toString();
		mv.addObject("msg", msg);
		mv.setViewName("msg");
		return mv;
	}

	/**
	 * 数据字典管理：跳转到编辑字典项页面
	 * @param userId
	 * @return
	 */
	@RequestMapping(value = "/toUpdate")
	public ModelAndView toEditPage(SysDicKey key, SysDic rec) {
		ModelAndView mv = new ModelAndView();
		SysDic dic = dicService.selectByPrimaryKey(key);
		mv.addObject("dic", dic);
		mv.setViewName("system/dic/updateDic");
		return mv;
	}

	/**
	 * 数据字典管理：编辑字典项
	 * @param userId
	 * @return
	 */
	@RequestMapping(value = "/update")
	public ModelAndView updateDic(SysDicKey key, SysDic rec,HttpServletResponse response, HttpServletRequest request) {
		BJuiJSON bjui = new BJuiJSON();
		ModelAndView mv = new ModelAndView();
		try {
			dicService.updateByPrimaryKeySelective(rec);
			
			bjui.setStatusCode("200");
			bjui.setMessage("更新成功！！！");
			bjui.setTabid("navtab-dic");
			bjui.setCloseCurrent(true);
		} catch (Exception e) {
			bjui.setStatusCode("300");
			bjui.setMessage("更新失败！！！");
		}
		String msg = JSONObject.fromObject(bjui).toString();
		mv.addObject("msg", msg);
		mv.setViewName("msg");
		return mv;
	}


	/**
	 * 数据字典管理：根据字典名称和父节点值查出对应的数据字典项   数据字典列表
	 * @param response
	 * @param request
	 * @return
	 */
	@SuppressWarnings("all")
	@RequestMapping(value = "/diclist")
	public ModelAndView getDicList(@ModelAttribute SysDic result,
			HttpServletResponse response, HttpServletRequest request) {
		
		//分页设置
		String pageCurrent = request.getParameter("pageCurrent");
		Page page =  new Page();
		if (StringUtils.isNotBlank(pageCurrent)) {
			page.setPageCurrent(Integer.parseInt(pageCurrent));
			result.setPage(page);
		}
		
		String dicCode = result.getDicCode();
		String parentValue = result.getParentValue();
		String itemName = result.getItemName();
		if (itemName == null) {
			itemName = "";
		}
		Map map = new HashMap();
		map.put("dicCode", dicCode);
		map.put("parentValue", parentValue);
		map.put("itemName", itemName.trim().toUpperCase());
		map.put("obj", result);
		List<SysDic> list = dicService.listPageForDic(map);
		if (list != null)
			for (SysDic dic : list) {
				if (dic.getParentValue() != null && !dic.getParentValue().equals("")) {
					Map mm = new HashMap();
					mm.put("itemValue", dic.getParentValue());
					mm.put("dicCode", dic.getDicCode());
					dic.setParentName(dicService.getItemNameByValue(mm));
				}

			}
		Map<String, Object> model = new HashMap<String, Object>();
		model.put("list", list);
		model.put("dic", result);
		model.put("page", result.getPage());
		model.put("parentValue", parentValue);
		model.put("dicCode", dicCode);
		return new ModelAndView("system/dic/diclist", model);
	}

	/**
	 * 数据字典管理：跳转到添加数据字典项页面
	 * @param result
	 * @return
	 */
	@RequestMapping(value = "/toAddDic")
	public ModelAndView gocreateDic(@ModelAttribute SysDic result) {
		Map<String, Object> model = new HashMap<String, Object>();
		SysDic dtd = dicService.getCodeAndName(result.getDicCode());
		result.setDicName(dtd.getDicName());
		model.put("dic", result);
		return new ModelAndView("system/dic/addDic", model);
	}
	/**
	 * 
	 * 问题来了
	 * 数据字典管理：删除数据字典
	 * @param result
	 * @return
	 */
	@RequestMapping(value = "/delete")
	public ModelAndView deleteUser(@ModelAttribute SysDic result, HttpServletResponse response,
			HttpServletRequest request) {
		BJuiJSON bjui = new BJuiJSON();
		ModelAndView mv = new ModelAndView();
		
		String delids = request.getParameter("delids");
		
		String [] ids= StrUtil.funsplit(delids);//转成数组
		Arrays.asList(ids);
		
		int k=0;
		for(int i=0;i<Arrays.asList(ids).size();i++){
			SysDic dic = new SysDic();
			dic.setDicCode(result.getDicCode());
			dic.setParentValue(Arrays.asList(ids).get(i));
			List<SysDic> list = dicService.selectLowerLevel(dic);
			if(null != list && list.size() > 0){
				bjui.setStatusCode("300");
				bjui.setMessage("删除失败，项目编号："+Arrays.asList(ids).get(i)+"有下级！！！");
				k++;
				break;
			}
		}
		if(k==0){
			try{
				dicService.deleteAll(result);
				
				bjui.setStatusCode("200");
				bjui.setMessage("删除成功！！！");
				bjui.setTabid("navtab-dic");
			}catch(Exception e){
				e.printStackTrace();
				bjui.setStatusCode("300");
				bjui.setMessage("删除失败！！！");
			}
		}
		String msg = JSONObject.fromObject(bjui).toString();
		mv.addObject("msg", msg);
		mv.setViewName("msg");
		return mv;
	}

	/**
	 * 根据数据字典的DIC_CODE获取字典项，返回到下拉列表框
	 * 
	 * @param dicCode
	 * @return
	 *//*
	@RequestMapping("/getOptionsList")
	public @ResponseBody List<Map<String, String>> getDicByDicCode(String param) {
		List<Map<String, String>> list = dicService.getDicByDicCode(param.toUpperCase());
		return list;
	}*/
	
}